package com.summer.utils.file.impl;

import com.summer.utils.file.LineFileService;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class LineFileServiceImpl implements LineFileService {

    @Override
    public Integer getLines(String filePath) {

        File sourceFile = new File(filePath);
        if (!sourceFile.exists()) {
            throw new RuntimeException("文件不存在，filePath="+filePath);
        }
        if (sourceFile.isDirectory()) {
            throw new RuntimeException("该地址不是文件");
        }
        try {
            InputStreamReader in = new InputStreamReader(new FileInputStream(filePath), "UTF-8");
            BufferedReader br = new BufferedReader(in);

            String tempData = br.readLine();
            int i = 1;
            while (tempData != null) {
                i++;
                tempData = br.readLine();
            }
            in.close();
            return Integer.valueOf(i);

        } catch (Exception e) {
            throw new RuntimeException("读取文件失败，e="+e.getMessage());
        }
    }

    @Override
    public Integer getLines(File file) {

        return getLines(file.getAbsolutePath());
    }
}
